package ru.compscicenter.databases.zaikina.httpserver;


public class Command {
    private final int commandType;
    private final String input;

    private static final String COMMAND_KEY = "command=";
    private static final String VALUE_KEY = "value=";
    private static final String DELIMITER = "&";

    public Command(int commandType) {
        this.commandType = commandType;
        this.input = null;
    }

    public Command(int commandType, String input) {
        this.commandType = commandType;
        this.input = input;
    }

    public int getCommandType() {
        return commandType;
    }

    public String getInput() {
        return input;
    }

    public static Command parse(String str) {
        String[] arr = str.split(DELIMITER);
        if (arr.length == 0) {
            return null;
        }

        int idx = arr[0].indexOf(COMMAND_KEY);
        if (idx == -1) {
            return null;
        }
        String strCommandType = arr[0].substring(idx + COMMAND_KEY.length(), arr[0].length());
        int command;
        try {
            command = Integer.parseInt(strCommandType);
        } catch (NumberFormatException ex) {
            return null;
        }

        String value;
        if (arr.length > 1) {
            idx = arr[1].indexOf(VALUE_KEY);
            if (idx != -1) {
                int endIdx = arr[1].substring(idx + VALUE_KEY.length(), arr[1].length()).indexOf(" ");
                if (endIdx == -1) {
                    endIdx = arr[1].length();
                }

                value = arr[1].substring(idx + VALUE_KEY.length(), endIdx);
                return new Command(command, value);
            }
        }
        return new Command(command);
    }

    public String toString() {
        return COMMAND_KEY + commandType + DELIMITER + VALUE_KEY + input;
    }
}
